package com.example.spider;

import ch.qos.logback.core.net.SyslogOutputStream;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ComicInfoProcessor implements PageProcessor {

    private static final String baseUrl = "http://comic2.kukudm.com/comiclist/1087";

    private Site site = Site.me().setTimeOut(30000).setRetryTimes(3).setSleepTime(500);

    private Map<String,String> hrefs = new HashMap<>();

    @Override
    public void process(Page page) {

        //判断是否有下一页标签页
        if(page.getHtml().xpath("//img[@src='/images/d.gif']/@src").toString() == null){
            //章节页面
            List<Selectable> aNodes = page.getHtml().xpath("//dl[@id='comiclistn']//a[starts-with(@href,'http://comic2.kukudm.com/comiclist/')]").nodes();

            for(Selectable node : aNodes){
                String partName = node.xpath("a/text()").toString();
                String href = node.xpath("a/@href").toString();
//                page.addTargetRequest(href);
                href = href.substring(0, href.lastIndexOf("/") + 1);
                hrefs.put(href, partName);
            }
            List<String> requests = page.getHtml().xpath("//dl[@id='comiclistn']//a[starts-with(@href,'http://comic2.kukudm.com/comiclist/')]/@href").all();
            page.addTargetRequests(requests);
//            page.putField("parts", hrefs);
            page.setSkip(true);
        }else{
            //漫画页，继续发现a标签
            List<String> links = page.getHtml().$("a").links().all();
            if (links.size() > 0)
                page.addTargetRequests(links);
            List<String> scripts = page.getHtml().xpath("//script[@language='javascript']").all();
            if(scripts.size() > 0){
                // 抓取内容
                String s = "\\+m201001d\\+\"";
                String a[] = scripts.get(scripts.size() - 1).split(s);
                if(a.length > 0){
                    String img = "http://v2.kukudm.com/" + a[1].split("'><span style='display:none'>")[0];
                    page.putField("img", img);
                    page.putField("parts", hrefs);
                }
            }
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {

        Spider.create(new ComicInfoProcessor())
                .addUrl(baseUrl + "/index.htm")
                .addPipeline(new MyPipeline())
                //开启5个线程抓取
                .thread(4)
                //启动爬虫
                .run();
    }
}
